package com.taiyi.sqltoy.starter.autoconfigure;

import com.taiyi.sqltoy.starter.context.UserContext;
import com.taiyi.sqltoy.starter.context.impl.ThreadLocalUserContext;
import com.taiyi.sqltoy.starter.handler.TaiyiUnifyFieldsHandler;
import com.taiyi.sqltoy.starter.properties.TaiyiSqlToyPlusProperties;
import lombok.extern.slf4j.Slf4j;
import org.sagacity.sqltoy.plugins.IUnifyFieldsHandler;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * Taiyi SqlToy Plus 自动配置类
 * 
 * @author taiyi
 * @since 1.0.0
 */
@Slf4j
@AutoConfiguration
@ConditionalOnClass({IUnifyFieldsHandler.class})
@ConditionalOnProperty(prefix = "taiyi.sqltoy.plus", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(TaiyiSqlToyPlusProperties.class)
public class TaiyiSqlToyPlusAutoConfiguration {

    /**
     * 配置默认的用户上下文实现
     */
    @Bean
    @ConditionalOnMissingBean(UserContext.class)
    public UserContext userContext() {
        log.info("Taiyi SqlToy Plus: 配置默认用户上下文(ThreadLocal)");
        return new ThreadLocalUserContext();
    }

    /**
     * 配置统一字段处理器
     */
    @Bean("taiyiUnifyFieldsHandler")
    @Primary
    @ConditionalOnProperty(prefix = "taiyi.sqltoy.plus", name = "enable-unify-fields", havingValue = "true", matchIfMissing = true)
    public IUnifyFieldsHandler taiyiUnifyFieldsHandler(
            TaiyiSqlToyPlusProperties properties,
            UserContext userContext) {
        
        log.info("Taiyi SqlToy Plus: 配置统一字段处理器");
        log.info("  - 统一字段功能: {}", properties.isEnableUnifyFields());
        log.info("  - 多租户功能: {}", properties.isEnableMultiTenant());
        log.info("  - 租户字段: {}", properties.getTenantField());
        log.info("  - 忽略租户过滤表: {}", properties.getIgnoreTenantTables());
        
        return new TaiyiUnifyFieldsHandler(properties, userContext);
    }

    /**
     * 配置用户上下文助手类
     */
    @Bean
    @ConditionalOnMissingBean
    public TaiyiUserContextHelper userContextHelper(UserContext userContext) {
        log.info("Taiyi SqlToy Plus: 配置用户上下文助手类");
        return new TaiyiUserContextHelper(userContext);
    }
}